import numpy as np
import pandas as pd

df = pd.DataFrame({'month': [1, 4, 1, 10],
                   'year': [2012, 2014, 2013, 2014],
                   'sale': [55, 40, 84, 31]})
"""
   month  year  sale
0      1  2012    55
1      4  2014    40
2      1  2013    84
3     10  2014    31
"""

# MultiIndex 的创建
mi = df.set_index(["year", "month"])
print(mi)
"""
            sale
year month      
2012 1        55
2014 4        40
2013 1        84
2014 10       31
"""
print(mi.index)
"""
MultiIndex([(2012,  1),
            (2014,  4),
            (2013,  1),
            (2014, 10)],
           names=['year', 'month'])
           
MultiIndex(levels=[[2012, 2013, 2014], [1, 4, 10]],
           labels=[[0, 2, 1, 2], [0, 1, 0, 2]],
           names=['year', 'month'])
"""
print(mi.index.names)  # ['year', 'month']
print(mi.index.levels)  # [[2012, 2013, 2014], [1, 4, 10]]

# MultiIndex 的创建
arrays = [[1, 1, 2, 2], ["r", "b", "r", "b"]]
print(pd.MultiIndex.from_arrays(arrays, names=("num", "col")))
"""
MultiIndex([(1, 'r'),
            (1, 'b'),
            (2, 'r'),
            (2, 'b')],
           names=['num', 'col'])
"""
